package com.cashmama.market.api.domain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.domain.integration.AdvanceAiIntegrationService;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApiErrorException;
import com.fqgj.xjd.user.client.UserInfoService;
import com.fqgj.xjd.user.client.UserOcrInfoService;
import com.fqgj.xjd.user.client.UserPanService;
import com.fqgj.xjd.user.client.enums.UserOcrTypeEnum;
import com.fqgj.xjd.user.client.request.UserBase;
import com.fqgj.xjd.user.client.request.UserOcrInfo;
import com.fqgj.xjd.user.client.request.UserPanSaveInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 2019-12-30
 * Time: 15:24
 */
@Service
public class PancardService {

    private static final Logger logger = LoggerFactory.getLogger(PancardService.class);
    @Autowired
    private ApolloConfigUtil apolloConfig;

    @Autowired
    private UserPanService userPanService;


    @Autowired
    private UserOcrInfoService userOcrInfoService;

    @Autowired
    private OSSService ossService;

    @Autowired
    private AdvanceAiIntegrationService advanceAiIntegrationService;

    @Autowired
    private UserInfoService userInfoService;


    public void save(String userCode, String cardNo, String frontImgUrl) {
        UserPanSaveInfo userPanInfo = new UserPanSaveInfo();
        userPanInfo.setUserCode(userCode);
        userPanInfo.setCardNo(cardNo);
        userPanInfo.setCardUrl(frontImgUrl);

        userPanInfo.setPanStatus("Y");  // 主要用于校验信息完整性
        Response response = userPanService.addUserPan(userPanInfo);

        if (!response.isSuccess()) {
            throw new ApplicationException(response.getCode(), response.getMsg());
        }
        //ocr
        asyncOcrV2(UserOcrTypeEnum.PAN_FRONT, frontImgUrl, userCode);
    }

    public void asyncOcrV2(UserOcrTypeEnum userOcrTypeEnum, String imgUrl, String userCode) {

        if (!apolloConfig.openApiOcr()) {
            return;
        }
        Response<String> ocrResponse = advanceAiIntegrationService.ocr(imgUrl);
        if (!ocrResponse.isSuccess()) {
            throw new ApiErrorException(apolloConfig.getPanCardOcrTip());
        }
        //上传数据到oss
        String fileName = "ocr/%s/%s_%s.json";
        fileName = String.format(fileName, userOcrTypeEnum.name(), userCode, DateUtil.getDate(new Date()));
        String dataUrl = apolloConfig.getQsyqBaseUrl() + ossService.uploadFile(fileName, ocrResponse.getData());

        UserOcrInfo userOcrInfo = new UserOcrInfo();
        userOcrInfo.setUserCode(userCode);
        userOcrInfo.setOcrResultUrl(dataUrl);
        userOcrInfo.setOcrType(userOcrTypeEnum);
        userOcrInfoService.saveUserOcrInfo(userOcrInfo);

        if (UserOcrTypeEnum.PAN_FRONT.equals(userOcrTypeEnum)) {
            JSONObject jsonObject = JSON.parseObject(HttpUtil.getPage(dataUrl));
            JSONObject card = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("card_info");
            String dateInfo = card.getString("date_info");
            if (StringUtils.isNotEmpty(dateInfo)) {
                Date birthday = com.fqgj.common.utils.DateUtil.getDate(dateInfo, "dd/MM/yyyy");
                UserBase userBase = new UserBase();
                userBase.setUserCode(userCode)
                        .setBirthday(com.fqgj.common.utils.DateUtil.getDate(birthday, "yyyy-MM-dd"));
                userInfoService.updateUserBase(userBase);
                logger.info("更新birthday,userBase:{}", JSON.toJSONString(userBase));
            }
        }
    }

}
